import 'dart:convert';
import 'package:injectable/injectable.dart';
import 'package:vista/shared/models/comment_shot.dart';
import 'package:vista/shared/models/like_frame.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/photo_params.dart';
import 'package:vista/shared/services/storage_service.dart';
import 'package:vista/shared/services/auth_focus.dart';

/// 发布工作室
/// 处理动态的发布、点赞、评论，如摄影工作室般管理内容
@lazySingleton
class PostStudio {
  final StorageService _storageService;
  final AuthFocus _authFocus;
  static const String _postsKey = 'posts';
  static const String _likesPrefix = 'likes_';
  static const String _commentsPrefix = 'comments_';
  static const String _isInitializedKey = 'posts_initialized';

  PostStudio(this._storageService, this._authFocus);

  /// 初始化默认动态数据
  /// 为每个分类创建3条动态，并创建一些点赞和评论数据
  Future<void> initializeDefaultPosts() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    final users = await _authFocus.getUsers();
    if (users.isEmpty) {
      return;
    }

    final now = DateTime.now();
    final defaultPosts = <MomentShot>[];
    final defaultLikes = <LikeFrame>[];
    final defaultComments = <CommentShot>[];

    // 确保至少有5个用户
    if (users.length < 5) {
      return;
    }

    final author0 = users[0];
    final author1 = users[1];
    final author2 = users[2];
    final liker0 = users[3];
    final liker1 = users[4];
    final commenter0 = users.length > 5 ? users[5] : users[3];
    final commenter1 = users.length > 6 ? users[6] : users[4];

    // ========== 日常生活分类动态 1 ==========
    final dailyPost1Id = 'post_${now.millisecondsSinceEpoch}_daily_0';
    final dailyPost1 = MomentShot(
      id: dailyPost1Id,
      authorId: author0.id,
      category: PostCategory.dailyLife,
      images: [
        'assets/images/dynamic10.png',
        'assets/images/dynamic11.png',
        'assets/images/dynamic12.png',
      ],
      content:
          'Freezing time with every click—love how portraits tell unique stories. #CaptureTheMoment',
      timestamp: now.subtract(const Duration(days: 0, hours: 0)),
      viewCount: 156,
    );
    defaultPosts.add(dailyPost1);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost1Id}_0',
        postId: dailyPost1Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 0, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost1Id}_1',
        postId: dailyPost1Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 0, minutes: 10)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost1Id}_0',
        postId: dailyPost1Id,
        userId: commenter0.id,
        content: 'Looks amazing!',
        timestamp: now.subtract(const Duration(days: 0, minutes: 15)),
      ),
    );

    // ========== 日常生活分类动态 2 ==========
    final dailyPost2Id = 'post_${now.millisecondsSinceEpoch}_daily_1';
    final dailyPost2 = MomentShot(
      id: dailyPost2Id,
      authorId: author1.id,
      category: PostCategory.dailyLife,
      images: [
        'assets/images/dynamic13.png',
        'assets/images/dynamic14.png',
        'assets/images/dynamic15.png',
      ],
      content:
          'Golden hour glow & genuine laughs—this shot feels like a warm hug. #HumanConnection',
      timestamp: now.subtract(const Duration(days: 1, hours: 2)),
      viewCount: 234,
    );
    defaultPosts.add(dailyPost2);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost2Id}_0',
        postId: dailyPost2Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 1, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost2Id}_1',
        postId: dailyPost2Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 1, minutes: 10)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost2Id}_2',
        postId: dailyPost2Id,
        userId: author0.id,
        timestamp: now.subtract(const Duration(days: 1, minutes: 20)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost2Id}_0',
        postId: dailyPost2Id,
        userId: commenter0.id,
        content: 'Great post!',
        timestamp: now.subtract(const Duration(days: 1, minutes: 15)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost2Id}_1',
        postId: dailyPost2Id,
        userId: commenter1.id,
        content: 'Nice!',
        timestamp: now.subtract(const Duration(days: 1, minutes: 30)),
      ),
    );

    // ========== 日常生活分类动态 3 ==========
    final dailyPost3Id = 'post_${now.millisecondsSinceEpoch}_daily_2';
    final dailyPost3 = MomentShot(
      id: dailyPost3Id,
      authorId: author2.id,
      category: PostCategory.dailyLife,
      images: [
        'assets/images/dynamic16.png',
        'assets/images/dynamic17.png',
        'assets/images/dynamic18.png',
      ],
      content:
          'Capturing raw moments—her smile says more than words ever could. #PortraitMagic #AuthenticVibes',
      timestamp: now.subtract(const Duration(days: 2, hours: 4)),
      viewCount: 189,
    );
    defaultPosts.add(dailyPost3);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost3Id}_0',
        postId: dailyPost3Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 2, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost3Id}_1',
        postId: dailyPost3Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 2, minutes: 10)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost3Id}_2',
        postId: dailyPost3Id,
        userId: author0.id,
        timestamp: now.subtract(const Duration(days: 2, minutes: 20)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${dailyPost3Id}_3',
        postId: dailyPost3Id,
        userId: author1.id,
        timestamp: now.subtract(const Duration(days: 2, minutes: 30)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost3Id}_0',
        postId: dailyPost3Id,
        userId: commenter0.id,
        content: 'Well done!',
        timestamp: now.subtract(const Duration(days: 2, minutes: 15)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost3Id}_1',
        postId: dailyPost3Id,
        userId: commenter1.id,
        content: 'Perfect!',
        timestamp: now.subtract(const Duration(days: 2, minutes: 30)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${dailyPost3Id}_2',
        postId: dailyPost3Id,
        userId: author0.id,
        content: 'Amazing!',
        timestamp: now.subtract(const Duration(days: 2, minutes: 45)),
      ),
    );

    // ========== 摄影分类动态 1 ==========
    final photoPost1Id = 'post_${now.millisecondsSinceEpoch}_photo_0';
    final photoPost1 = MomentShot(
      id: photoPost1Id,
      authorId: author0.id,
      category: PostCategory.photography,
      images: [
        'assets/images/dynamic1.png',
        'assets/images/dynamic2.png',
        'assets/images/dynamic3.png',
      ],
      content:
          'Captured this stunning sunset today. The golden hour light was absolutely perfect for this shot.',
      photoParams: PhotoParams(
        lens: '22.4 mm f/2.8',
        fl: '8',
        flash: 'off',
        exposure: 'Manual',
        camera: 'DJI FC3411',
        iso: '100',
        shutter: '1/100s',
        aperture: 'f/2.8',
      ),
      timestamp: now.subtract(const Duration(days: 3, hours: 0)),
      viewCount: 312,
    );
    defaultPosts.add(photoPost1);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost1Id}_0',
        postId: photoPost1Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 3, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost1Id}_1',
        postId: photoPost1Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 3, minutes: 10)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost1Id}_2',
        postId: photoPost1Id,
        userId: author1.id,
        timestamp: now.subtract(const Duration(days: 3, minutes: 20)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost1Id}_0',
        postId: photoPost1Id,
        userId: commenter0.id,
        content: 'Great composition!',
        timestamp: now.subtract(const Duration(days: 3, minutes: 15)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost1Id}_1',
        postId: photoPost1Id,
        userId: commenter1.id,
        content: 'The lighting is perfect!',
        timestamp: now.subtract(const Duration(days: 3, minutes: 30)),
      ),
    );

    // ========== 摄影分类动态 2 ==========
    final photoPost2Id = 'post_${now.millisecondsSinceEpoch}_photo_1';
    final photoPost2 = MomentShot(
      id: photoPost2Id,
      authorId: author1.id,
      category: PostCategory.photography,
      images: [
        'assets/images/dynamic4.png',
        'assets/images/dynamic5.png',
        'assets/images/dynamic6.png',
      ],
      content:
          'Experimenting with macro photography. The details you can capture up close are truly fascinating.',
      photoParams: PhotoParams(
        lens: '50 mm f/1.8',
        fl: '50',
        flash: 'off',
        exposure: 'Aperture Priority',
        camera: 'Canon EOS R5',
        iso: '200',
        shutter: '1/250s',
        aperture: 'f/1.8',
      ),
      timestamp: now.subtract(const Duration(days: 4, hours: 2)),
      viewCount: 278,
    );
    defaultPosts.add(photoPost2);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost2Id}_0',
        postId: photoPost2Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 4, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost2Id}_1',
        postId: photoPost2Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 4, minutes: 10)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost2Id}_2',
        postId: photoPost2Id,
        userId: author0.id,
        timestamp: now.subtract(const Duration(days: 4, minutes: 20)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost2Id}_3',
        postId: photoPost2Id,
        userId: author2.id,
        timestamp: now.subtract(const Duration(days: 4, minutes: 30)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost2Id}_0',
        postId: photoPost2Id,
        userId: commenter0.id,
        content: 'Amazing details!',
        timestamp: now.subtract(const Duration(days: 4, minutes: 15)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost2Id}_1',
        postId: photoPost2Id,
        userId: commenter1.id,
        content: 'Love the depth of field!',
        timestamp: now.subtract(const Duration(days: 4, minutes: 30)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost2Id}_2',
        postId: photoPost2Id,
        userId: author0.id,
        content: 'Beautiful work!',
        timestamp: now.subtract(const Duration(days: 4, minutes: 45)),
      ),
    );

    // ========== 摄影分类动态 3 ==========
    final photoPost3Id = 'post_${now.millisecondsSinceEpoch}_photo_2';
    final photoPost3 = MomentShot(
      id: photoPost3Id,
      authorId: author2.id,
      category: PostCategory.photography,
      images: [
        'assets/images/dynamic7.png',
        'assets/images/dynamic8.png',
        'assets/images/dynamic9.png',
      ],
      content:
          'Street photography in the city. Love capturing candid moments and the energy of urban life.',
      photoParams: PhotoParams(
        lens: '24-70 mm f/2.8',
        fl: '35',
        flash: 'on',
        exposure: 'Shutter Priority',
        camera: 'Nikon D850',
        iso: '400',
        shutter: '1/60s',
        aperture: 'f/2.8',
      ),
      timestamp: now.subtract(const Duration(days: 5, hours: 4)),
      viewCount: 421,
    );
    defaultPosts.add(photoPost3);

    // 点赞
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost3Id}_0',
        postId: photoPost3Id,
        userId: liker0.id,
        timestamp: now.subtract(const Duration(days: 5, minutes: 0)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost3Id}_1',
        postId: photoPost3Id,
        userId: liker1.id,
        timestamp: now.subtract(const Duration(days: 5, minutes: 10)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost3Id}_2',
        postId: photoPost3Id,
        userId: author0.id,
        timestamp: now.subtract(const Duration(days: 5, minutes: 20)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost3Id}_3',
        postId: photoPost3Id,
        userId: author1.id,
        timestamp: now.subtract(const Duration(days: 5, minutes: 30)),
      ),
    );
    defaultLikes.add(
      LikeFrame(
        id: 'like_${now.millisecondsSinceEpoch}_${photoPost3Id}_4',
        postId: photoPost3Id,
        userId: commenter0.id,
        timestamp: now.subtract(const Duration(days: 5, minutes: 40)),
      ),
    );

    // 评论
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost3Id}_0',
        postId: photoPost3Id,
        userId: commenter0.id,
        content: 'Perfect timing!',
        timestamp: now.subtract(const Duration(days: 5, minutes: 15)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost3Id}_1',
        postId: photoPost3Id,
        userId: commenter1.id,
        content: 'Great street photography!',
        timestamp: now.subtract(const Duration(days: 5, minutes: 30)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost3Id}_2',
        postId: photoPost3Id,
        userId: author0.id,
        content: 'Wonderful capture!',
        timestamp: now.subtract(const Duration(days: 5, minutes: 45)),
      ),
    );
    defaultComments.add(
      CommentShot(
        id: 'comment_${now.millisecondsSinceEpoch}_${photoPost3Id}_3',
        postId: photoPost3Id,
        userId: author1.id,
        content: 'Excellent shot!',
        timestamp: now.subtract(const Duration(days: 5, minutes: 60)),
      ),
    );

    // 保存所有数据
    await _savePosts(defaultPosts);
    await _saveLikes(defaultLikes);
    await _saveComments(defaultComments);
    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 保存动态列表
  Future<void> _savePosts(List<MomentShot> posts) async {
    final postsJson = posts.map((post) => post.toJson()).toList();
    final postsString = jsonEncode(postsJson);
    await _storageService.persistString(_postsKey, postsString);
  }

  /// 获取所有动态
  Future<List<MomentShot>> getAllPosts() async {
    final postsString = await _storageService.retrieveString(_postsKey);
    if (postsString == null) {
      return [];
    }

    try {
      final List<dynamic> postsJson = jsonDecode(postsString);
      return postsJson
          .map((json) => MomentShot.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 根据分类获取动态
  Future<List<MomentShot>> getPostsByCategory(PostCategory category) async {
    final allPosts = await getAllPosts();
    return allPosts.where((post) => post.category == category).toList();
  }

  /// 根据ID获取动态
  Future<MomentShot?> getPostById(String postId) async {
    final allPosts = await getAllPosts();
    try {
      return allPosts.firstWhere((post) => post.id == postId);
    } catch (e) {
      return null;
    }
  }

  /// 根据用户ID获取动态
  Future<List<MomentShot>> getPostsByUser(String userId) async {
    final allPosts = await getAllPosts();
    return allPosts.where((post) => post.authorId == userId).toList();
  }

  /// 获取用户点赞的动态列表
  Future<List<MomentShot>> getLikedPostsByUser(String userId) async {
    final allPosts = await getAllPosts();
    final likedPosts = <MomentShot>[];

    for (final post in allPosts) {
      if (await isLiked(post.id, userId)) {
        likedPosts.add(post);
      }
    }

    // 按时间倒序排序
    likedPosts.sort((a, b) => b.timestamp.compareTo(a.timestamp));
    return likedPosts;
  }

  /// 发布动态
  Future<MomentShot> publishPost({
    required String authorId,
    required PostCategory category,
    required List<String> images,
    required String content,
    PhotoParams? photoParams,
  }) async {
    if (images.length != 3) {
      throw Exception('Must upload exactly 3 images');
    }

    if (category == PostCategory.photography && photoParams == null) {
      throw Exception('Photography posts require photo parameters');
    }

    final post = MomentShot(
      id: 'post_${DateTime.now().millisecondsSinceEpoch}_$authorId',
      authorId: authorId,
      category: category,
      images: images,
      content: content,
      photoParams: photoParams,
      timestamp: DateTime.now(),
      viewCount: 0, // 新发布的动态访问次数为0
    );

    final allPosts = await getAllPosts();
    allPosts.insert(0, post);
    await _savePosts(allPosts);

    return post;
  }

  /// 保存点赞列表
  Future<void> _saveLikes(List<LikeFrame> likes) async {
    final likesByPost = <String, List<LikeFrame>>{};
    for (final like in likes) {
      likesByPost.putIfAbsent(like.postId, () => []).add(like);
    }

    for (final entry in likesByPost.entries) {
      final key = '$_likesPrefix${entry.key}';
      final likesJson = entry.value.map((like) => like.toJson()).toList();
      final likesString = jsonEncode(likesJson);
      await _storageService.persistString(key, likesString);
    }
  }

  /// 获取动态的点赞列表
  Future<List<LikeFrame>> getLikes(String postId) async {
    final key = '$_likesPrefix$postId';
    final likesString = await _storageService.retrieveString(key);
    if (likesString == null) {
      return [];
    }

    try {
      final List<dynamic> likesJson = jsonDecode(likesString);
      return likesJson
          .map((json) => LikeFrame.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 获取动态的点赞数量
  Future<int> getLikeCount(String postId) async {
    final likes = await getLikes(postId);
    return likes.length;
  }

  /// 检查用户是否已点赞
  Future<bool> isLiked(String postId, String userId) async {
    final likes = await getLikes(postId);
    return likes.any((like) => like.userId == userId);
  }

  /// 点赞动态
  Future<void> likePost(String postId, String userId) async {
    if (await isLiked(postId, userId)) {
      return; // 已经点赞过了
    }

    final likes = await getLikes(postId);
    likes.add(
      LikeFrame(
        id: 'like_${DateTime.now().millisecondsSinceEpoch}_$postId',
        postId: postId,
        userId: userId,
        timestamp: DateTime.now(),
      ),
    );

    final key = '$_likesPrefix$postId';
    final likesJson = likes.map((like) => like.toJson()).toList();
    final likesString = jsonEncode(likesJson);
    await _storageService.persistString(key, likesString);
  }

  /// 取消点赞
  Future<void> unlikePost(String postId, String userId) async {
    final likes = await getLikes(postId);
    likes.removeWhere((like) => like.userId == userId);

    final key = '$_likesPrefix$postId';
    if (likes.isEmpty) {
      await _storageService.removeKey(key);
    } else {
      final likesJson = likes.map((like) => like.toJson()).toList();
      final likesString = jsonEncode(likesJson);
      await _storageService.persistString(key, likesString);
    }
  }

  /// 保存评论列表
  Future<void> _saveComments(List<CommentShot> comments) async {
    final commentsByPost = <String, List<CommentShot>>{};
    for (final comment in comments) {
      commentsByPost.putIfAbsent(comment.postId, () => []).add(comment);
    }

    for (final entry in commentsByPost.entries) {
      final key = '$_commentsPrefix${entry.key}';
      final commentsJson =
          entry.value.map((comment) => comment.toJson()).toList();
      final commentsString = jsonEncode(commentsJson);
      await _storageService.persistString(key, commentsString);
    }
  }

  /// 获取动态的评论列表
  Future<List<CommentShot>> getComments(String postId) async {
    final key = '$_commentsPrefix$postId';
    final commentsString = await _storageService.retrieveString(key);
    if (commentsString == null) {
      return [];
    }

    try {
      final List<dynamic> commentsJson = jsonDecode(commentsString);
      return commentsJson
          .map((json) => CommentShot.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => a.timestamp.compareTo(b.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 获取动态的评论数量
  Future<int> getCommentCount(String postId) async {
    final comments = await getComments(postId);
    return comments.length;
  }

  /// 添加评论
  Future<CommentShot> addComment({
    required String postId,
    required String userId,
    required String content,
  }) async {
    final comment = CommentShot(
      id: 'comment_${DateTime.now().millisecondsSinceEpoch}_$postId',
      postId: postId,
      userId: userId,
      content: content,
      timestamp: DateTime.now(),
    );

    final comments = await getComments(postId);
    comments.add(comment);

    final key = '$_commentsPrefix$postId';
    final commentsJson = comments.map((c) => c.toJson()).toList();
    final commentsString = jsonEncode(commentsJson);
    await _storageService.persistString(key, commentsString);

    return comment;
  }

  /// 删除评论
  Future<void> deleteComment(String commentId, String postId) async {
    final comments = await getComments(postId);
    comments.removeWhere((comment) => comment.id == commentId);

    final key = '$_commentsPrefix$postId';
    if (comments.isEmpty) {
      await _storageService.removeKey(key);
    } else {
      final commentsJson = comments.map((c) => c.toJson()).toList();
      final commentsString = jsonEncode(commentsJson);
      await _storageService.persistString(key, commentsString);
    }
  }

  /// 增加动态的访问次数
  Future<void> incrementViewCount(String postId) async {
    final allPosts = await getAllPosts();
    final postIndex = allPosts.indexWhere((post) => post.id == postId);
    if (postIndex == -1) {
      return; // 动态不存在
    }

    final post = allPosts[postIndex];
    final updatedPost = MomentShot(
      id: post.id,
      authorId: post.authorId,
      category: post.category,
      images: post.images,
      content: post.content,
      photoParams: post.photoParams,
      timestamp: post.timestamp,
      viewCount: post.viewCount + 1,
    );

    allPosts[postIndex] = updatedPost;
    await _savePosts(allPosts);
  }

  /// 获取动态的访问次数
  Future<int> getViewCount(String postId) async {
    final allPosts = await getAllPosts();
    final post = allPosts.firstWhere(
      (post) => post.id == postId,
      orElse:
          () => MomentShot(
            id: '',
            authorId: '',
            category: PostCategory.dailyLife,
            images: [],
            content: '',
            timestamp: DateTime.now(),
          ),
    );
    return post.viewCount;
  }

  /// 删除动态
  Future<void> deletePost(String postId) async {
    final allPosts = await getAllPosts();
    allPosts.removeWhere((post) => post.id == postId);
    await _savePosts(allPosts);

    // 同时删除相关的点赞和评论
    final likesKey = '$_likesPrefix$postId';
    await _storageService.removeKey(likesKey);

    final commentsKey = '$_commentsPrefix$postId';
    await _storageService.removeKey(commentsKey);
  }
}
